import requests
from ETP.commons.APIError import APIError
from ETP.models import Step
import logging
logger = logging.getLogger(__name__)
collect_logger = logging.getLogger("collect")


class RequestHttp:

    def run_api(self,step_id):
        step = Step.objects.get(id=step_id)
        if step.api_method == 'POST':
            self.post_request(step)
        else:
            self.get_request(step)

    def get_request(self,step):
        api_url = step.api_url
        params = step.api_params
        request_url = api_url + params
        expect = step.api_expect
        try:
            r = requests.get(request_url)
            if r.status_code == 200:
                res = r.text
                logger.info("服务器返回响应：%s"%res)
                if res == expect:
                    logger.info('执行成功')
                    step.result = 'SUCCESS'
                else:
                    step.result = 'FAILURE'
                    logger.info('请求成功，数据比对不一致，请验证')
            else:
                step.result = 'FAILURE'
                logger.error('服务器返回状态失败，请查看接口配置是否与接口文档一致')
                raise APIError('接口状态:%d,请查看接口置是否与接口文档一致'%r.status_code)
        except Exception as e:
            step.result = "FAILURE"
            raise Exception('请求服务器失败，请查看URL或服务器状态')



    def post_request(self,step):
        api_url = step.api_url
        json_str = step.api_json
        api_header = step.api_header
        expect = step.api_expect
        try:
            r = requests.post(url=api_url,data=json_str)
            if r.status_code == 200:
                res = r.text
                logger.info("服务器返回响应：%s"%res)
                if res == expect:
                    logger.info('执行成功')
                    step.result = 'SUCCESS'
                else:
                    step.result = 'FAILURE'
                    logger.error('服务器返回状态失败，请查看接口配置是否与接口文档一致')
                    raise APIError('接口状态：%d,请查看接口配置是否与接口文档一致'%r.status_code)
        except Exception as e:
            step.result = 'FAILURE'
            raise Exception('请求服务器失败，请查看URL或服务器状态')



